var express = require('express');
var router = express.Router();
//var Post=require('../models/post');

var Acount = require('../models/acount');
var UserAcount = require('../models/user_acount');
var Singer = require('../models/signer');
var globals = require('../models/videos');

var MailUtil = require('../mail');
var Util = require('../util');
var auth = require('../auth');


/* GET users listing. */
//router.get('/:uid', function(req, res, next) {
//  if(req.session.user.name!=req.params.uid)  {
//      req.session.message="用户不存在";
//      return res.redirect('/');
//  }
//  Post.find({user:req.params.uid},function(err,posts){
//      if(err){
//          req.session.message=err.message;
//          return res.redirect('/');
//      }
//      res.render('user',{
//          title:"发表文章",
//          username:req.params.uid,
//          posts:posts
//      });
//  });
//
//});


//mongooseModel.update(conditions, update, options, callback);
//var conditions = {username : 'model_demo_username'};
//var update     = {$set : {age : 27, title : 'model_demo_title_update'}};
//var options    = {upsert : true};
//mongooseModel.update(conditions, update, options, function(error){
//    if(error) {
//        console.log(error);
//    } else {
//        console.log('update ok!');
//    }
//    //关闭数据库链接
//    db.close();
//});

// 更新账号状态&获取视频账号
router.post('/close', isLogin);
router.post('/close', function (req, res, next) {
    console.log('acount close ');


    UserAcount.findOne({username: req.session.user.name}, function (err, useracount) {

        if (useracount) {

            console.log('find useracount success, useracount_id:'+useracount.id);

            Acount.update({acount_name:useracount.acount_name},{$set:{is_used: false }}, function(err, acount){

                if (!err){
                    console.log('acount udpate success '+ acount.is_used ? "true":"false");

                }else {
                    console.log('acount udpate err '+ err);

                }
            });

            //
            //Acount.findOneAndUpdate({acount_name:acount.acount_name}, acount,function(err, doc){
            //
            //    if (!err) {
            //
            //        console.log(' acount update success');
            //
            //    }else {
            //        console.log(' acount update falure:'+err);
            //    }
            //
            //});
            //
            //Acount.findByIdAndUpdate(useracount.id, { $set: { is_used: false }}, { new: true }, function (err, acount) {
            //    if (err) {
            //        console.log('findByIdAndUpdate err');
            //
            //        //return handleError(err);
            //    }else {
            //        console.log('findByIdAndUpdate success:'+acount);
            //    }
            //
            //
            //});


            useracount.remove();

        }else {

            console.log('no useracount ');

        }

        return res.json({
            videos: globals.videos,
            code: 0
        });


    });

})



// 获取用户当前使用视频账号
router.get('/getacount', isLogin)
router.get('/getacount', function (req, res, next) {

    UserAcount.findOne({username: req.session.user.name}, function (err, useracount) {

        if (!err) {

            console.log('not error');
            if (useracount) {

                console.log('find useracount object '+useracount);


                Acount.findOne({acount_name: useracount.acount_name}, function(err, acount) {

                    if(!err) {

                        return res.json({
                            acountname: acount.acount_name,
                            password: acount.password,
                            code: 0
                        })

                    }else {
                        console.log('not found acount')
                    }

                })



            }else {

                console.log('not find useracount object ');
                return res.json({
                    videos: globals.videos,
                    code: 0
                })

            }

        }

    })

})

// 更新账号状态&获取视频账号
router.get('/acount', isLogin);
router.get('/acount', function (req, res, next) {
    console.log('acount get ' + req.param('type_id'));

    var type_id = req.param('type_id');

    Acount.findOne({type_id: type_id, is_used: false}, function (err, acount) {

        if (!err) {
            if (acount) {
                console.log('find acount success');

                acount.is_used = true;

                Acount.findOneAndUpdate({acount_name:acount.acount_name}, acount,function(err, doc){

                    if (!err) {

                        console.log(' acount update success');

                    }else {
                        console.log(' acount update falure:'+err);
                    }

                });

                UserAcount.findOne({username: req.session.user.name}, function (err, useracount) {

                    if (useracount) {

                        console.log('find useracount success');

                        //videos.forEach(function(video,i,arr){
                        //
                        //})

                        useracount.acount_name = acount.acount_name;

                        useracount.type_id = type_id;
                        useracount.times += 1;

                        UserAcount.findOneAndUpdate({username: req.session.user.name}, useracount, function (err, object){

                            if (!err) {

                                console.log(' UserAcount update success');

                            }
                        });

                    }else {

                        console.log('no useracount ');

                        var useracount1 = new UserAcount;

                        useracount1.type_id = acount.type_id;
                        useracount1.username = req.session.user.name;
                        useracount1.acount_name = acount.acount_name;
                        useracount1.times = 1;

                        useracount1.save();

                    }

                    return res.json({
                        type_id: acount.type_id,
                        videos: globals.videos,
                        acountname: acount.acount_name,
                        password: acount.password,
                        code: 0
                    })


                });
            }else {
                console.log('not acount');
            }

        }else {
            console.log('account err:'+err);
        }


    });

});

router.post('/create_acount', isLogin);
router.post('/create_acount', function (req, res) {

    var useracount = new UserAcount;
    useracount.username = req.session.user.name;
    useracount.type_id = req.body.type_id;

    useracount.save();

    res.json({
        type_id:req.body.type_id,
        code: 0
    })
});


//home 初始化获取账号
router.get('/getacounts', isLogin);
router.get('/getacounts', function (req, res) {

    auth.queryurl(req, res);

    var username = req.session.user.name;

    console.log(username);

    UserAcount.findOne({username: username}, function (err, acount) {

        if (!err) {
            console.log('not error');
            if (acount) {

                console.log('find useracount object '+acount);

                return res.json({
                    type_id: acount.type_id,
                    videos: globals.videos,
                    code: 0
                })

            }else {

                console.log('not find useracount object ');
                return res.json({
                    videos: globals.videos,
                    code: 0
                })

            }

        }

    });

})


router.post('/findAndUpdatePwd',function(req, res) {

    console.log('findAndUpdatePwd');
    var name = "1398905782@qq.com";

    var to = req.body.mailnumber;
    var from = '13717535178@163.com';


    var subject = '[找回密码]';

    var time = 24;

    var  randkey = Util.randPwd();

    var sign = Util.sign(name, time, randkey);
    var md5 = Util.MD5(sign);
    var url = 'sid='+md5 +'&username='+name;
    var host = 'http://127.0.0.1:3000/ensurepwd';
    var text = host +'?' + url;

    MailUtil.send(from, subject, to ,text);

    res.redirect('/');

    //return res.json({
    //
    //    code: 0
    //});
});
router.get('/findpwd', function(req, res) {

    res.render('findpwd',{});
});


function isLogin(req, res, next) {
    if (!req.session.user) {

        return res.redirect('/');
    }
    next();
}
module.exports = router;
